#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from selenium.webdriver.common.keys import Keys
from PageObjects.WebWeiXin.WXBasePage import WXBasePage
from Utils.Element import Element
from Utils.PropertiesParsor import ParsePageProperty
from Config.GlobalVariables import OPERATION_ATTEMPT
import time

parse_string = ParsePageProperty().parse_string
parse_locator = ParsePageProperty().parse_locator
set_property_value = ParsePageProperty().set_property_value


class WXHomePage(WXBasePage):

    @staticmethod
    def parse_url():
        return parse_string('WebWeiXin.HomePage.url')

    @staticmethod
    def parse_title():
        return parse_string('WebWeiXin.HomePage.title')

    @staticmethod
    def contact_to(name):
        return parse_string('WebWeiXin.HomePage.contact_to').format(name)

    def chat_tab(self):
        return Element(self.driver, parse_locator('WebWeiXin.HomePage.chat_tab'))

    def contact_tab(self):
        return Element(self.driver, parse_locator('WebWeiXin.HomePage.contact_tab'))

    def search_textbox(self):
        return Element(self.driver, parse_locator('WebWeiXin.HomePage.search_textbox'))

    def search_result_list(self, contact_name):
        locate_type = parse_locator('WebWeiXin.HomePage.search_result_list')[0]
        locate_expression = parse_locator('WebWeiXin.HomePage.search_result_list')[1].format(contact_name)
        return Element(self.driver, (locate_type, locate_expression))

    def chat_area_title(self):
        return Element(self.driver, parse_locator('WebWeiXin.HomePage.chat_area_title'))

    def edit_area(self):
        return Element(self.driver, parse_locator('WebWeiXin.HomePage.edit_area'))

    def set_cookies_opt(self):
        self.logger.info("Set Web WeiXin Cookies")
        try:
            if self.chat_tab().is_displayed():
                self.logger.debug("Get Page Cookies Successfully")
                cookies = self.driver.get_cookies()
                self.logger.debug("Set Page Cookies Into PageProperty Cookies")
                set_property_value("WebWeiXin.HomePage.cookies", cookies)
            else:
                self.logger.debug("Set Empty List Into PageProperty Cookies")
                set_property_value("WebWeiXin.HomePage.cookies", [])
        except Exception as e:
            self.logger.error("Failed To Set Cookies Property: {0}".format(e))
            raise e

    def go_(self):
        self.logger.info("Let's Go Web WeiXin")
        self.browser.new_window(parse_string("WebWeiXin.HomePage.url"))
        self.browser.switch_to_last_window()
        cookies = parse_string("WebWeiXin.HomePage.cookies")
        if cookies:
            self.logger.debug("Add cookies to page and refresh")
            for cookie in cookies:
                self.add_cookie(cookie)
            self.browser.refresh()
            return True
        else:
            for login_attempt in range(OPERATION_ATTEMPT):
                self.logger.debug("Check whether Web WeiXin is logged in")
                if self.chat_tab().is_displayed():
                    self.logger.debug("Web WeiXin is logged in")
                    return True
                else:
                    self.logger.info("Login NO.{0} Attempts".format(login_attempt + 1))
            return False

    def go(self):
        if not self.go_():
            self.logger.error("Cannot Login In {0} Attempts, Quit".format(OPERATION_ATTEMPT))
            self.browser.close()
            self.browser.switch_to_first_window()
            return False
        else:
            self.set_cookies_opt()
            if parse_string("WebWeiXin.HomePage.cookies"):
                self.logger.error("Fail To Set Page Cookies, Quit")
                self.browser.close()
                self.browser.switch_to_first_window()
                return False
            else:
                self.logger.info("Login And Set Page Cookies Successfully")
                self.browser.close()
                self.browser.switch_to_first_window()
                return True

    def send_messages_(self, target_contact, message_content):
        self.logger.info("Click search textbox")
        self.search_textbox().click()
        self.logger.info("Input target contact in search textbox")
        self.search_textbox().clear()
        self.search_textbox().send_keys(target_contact)
        self.search_result_list(target_contact).click()
        if target_contact == self.chat_area_title().get_text():
            self.logger.info("Input message content in edit area and submit")
            self.edit_area().clear()
            self.edit_area().send_keys(message_content)
            self.edit_area().send_keys(Keys.ENTER)
        else:
            self.logger.error("Target contact is not equal to chat area title")
            raise NameError

    def send_messages(self, webwx_window_index, target_contact, message_content):
        try:
            current_window = self.driver.current_window_handle
            self.browser.switch_to_specific_window(webwx_window_index)
            self.send_messages_(target_contact, message_content)
            self.driver.switch_to.window(current_window)
        except Exception as e:
            self.logger.error("Cannot send messages via Web WeiXin")
            raise e


if __name__ == '__main__':
    print(parse_locator('WebWeiXin.HomePage.search_textbox'))
    print(parse_locator('WebWeiXin.HomePage.edit_area'))
    print(WXHomePage("123").edit_area())
